import React, { useEffect, useState } from 'react';
import { Tree } from 'antd';
import { useEditor } from '@craftjs/core';
import { generateSerializedNodes } from '../../../tools';
import styles from './index.less';

export default ({ visible }) => {
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [treeNodes, setTreeNodes] = useState([]);
  const {
    connectors: { hover },
    actions: { selectNode },
    selectedKey,
    serializedNodes,
  } = useEditor((state, query) => {
    const currentSelectedId = query.getEvent('selected').last();
    return { serializedNodes: query.getSerializedNodes(), selectedKey: currentSelectedId };
  });

  useEffect(() => {
    if (visible) {
      const { nodeTree, parentKeys } = generateSerializedNodes(serializedNodes);
      setTreeNodes(nodeTree);
      setExpandedKeys(parentKeys);
      setSelectedKeys(selectedKey ? [selectedKey] : []);
    }
  }, [visible]);

  return (
    <div className={styles.resumeTreeContent}>
      <Tree
        defaultExpandAll
        treeData={treeNodes}
        selectedKeys={selectedKeys}
        expandedKeys={expandedKeys}
        showLine={{ showLeafIcon: false }}
        onExpand={(nextExpandedKeys) => setExpandedKeys(nextExpandedKeys)}
        titleRender={({ key, title }) => {
          return (
            <span
              key={key}
              title={title}
              className={styles.treeNodeTitle}
              ref={(ref) => hover(ref, key)}
              onClick={() => {
                setSelectedKeys((prevKeys) => {
                  const nextKeys = [...prevKeys];
                  if (_.includes(nextKeys, key)) {
                    selectNode(null);
                    return [];
                  } else {
                    selectNode(key);
                    return [key];
                  }
                });
              }}
            >
              <span className={styles.treeNodeTitleText}>{title}</span>
            </span>
          );
        }}
      />
    </div>
  );
};
